Skip to content

ps1: gpu: Ensure hi >= lo when calling std::clamp() #1851

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 22, 2025

Conversation

thentenaar
Copy link
Contributor

@thentenaar thentenaar commented Feb 21, 2025

On Lunar Disc 1, when entering Berg (about two minutes in,) going into Alex's house or the barn to the right of it, winds up causing an assertion failure in std::clamp() on the screen transition. Could be a bug in the game where it sends the 0xe3/0xe4 coords in the wrong order, or if it's off by one calculating them. Not sure if the real hardware ignores it or does anything in particular as a result.

Adding some print() calls in GPU::Render::triangle() before the clamp, I see:

v0=(320,216), v1=(336,216) v2=(320,232)
vmin.x=320, x1=160 x2=159
vmin.y=216, y1=112 y2=111
vmax.x=336, x1=160 x2=159
vmax.y=232, y1=112 y2=111

/usr/lib/gcc/x86_64-pc-linux-gnu/14/include/g++-v14/bits/stl_algo.h:3626: constexpr const _Tp& std::clamp(const _Tp&, const _Tp&, const _Tp&) [with _Tp = int]: Assertion '!(__hi < __lo)' failed.

Thus, this patch ensures hi >= lo.

@LukeUsher
Copy link
Member

There's probably a more correct solution to this but it'l d for now to avoid the crash; sorry for the delay, I meant to investigate further but did not find the time just yet.

@LukeUsher LukeUsher merged commit 3d88e24 into ares-emulator:master Apr 22, 2025
@jcm93
Copy link
Contributor

jcm93 commented Apr 22, 2025

Just an aside, definitely not a fan of the macro function usage. Better would probably be something like:

constexpr auto clip = [](auto x, auto lo, auto hi) {
  return std::clamp((x), (((lo) <= (hi)) ? (lo) : (hi)), (((hi) >= (lo)) ? (hi) : (lo)));
};

Which is not only actually debuggable and devoid of macro side effects, but would also give you the ability to do things at compile time like

static_assert(clip(3, 1, 2) == 2);
static_assert(clip(1, 2, 3) == 2);
static_assert(clip(2, 1, 3) == 2);

Since it's localized here and maybe likely to be rewritten, I guess it's not terribly consequential, but it would be definitely be nicer if we take advantage of modern language features like this instead of macro functions in general in the future, I guess.

@thentenaar thentenaar deleted the ps1-gpu-clamp-fix branch April 22, 2025 17:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

3 participants